package com.mytijian.openapi.core.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
	
	private MD5(){}

	public static String stringMD5(String param)  {
		try {
	        MessageDigest messageDigest = MessageDigest.getInstance("MD5");  
	        byte[] inputByteArray = param.getBytes("utf-8");  
	        messageDigest.update(inputByteArray);
	        byte[] resultByteArray = messageDigest.digest();  
	        return byteArrayToHex(resultByteArray);  
		} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
			// no-op
			// 因为信息摘要算法 和 字符串编码类型都是常量，所以这两个异常不会发生
			throw new RuntimeException("MD5计算失败", e);
		}
	 }
	
	 public static String byteArrayToHex(byte[] byteArray) {  
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };  
        char[] resultCharArray =new char[byteArray.length * 2];  
        int index = 0; 
        for (byte b : byteArray) {  
           resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];  
           resultCharArray[index++] = hexDigits[b& 0xf];  
        }
        return new String(resultCharArray);  
    }
}
